package com.zbkj.client.controller;

import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.MaterialService;
import com.zbkj.client.service.KnowledgeService;
import com.zbkj.client.service.PieceService;
import com.zbkj.common.model.assets.Material;
import com.zbkj.common.model.assets.Knowledge;
import com.zbkj.common.response.client.AssetCountResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.common.utils.FileDownloadUtil;
import com.zbkj.client.vo.FileResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import org.springframework.http.ResponseEntity;

@Slf4j
@RestController
@RequestMapping("/api/client/common")
@Api(tags = "通用功能")
public class CommonController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private PieceService pieceService;

    @ApiOperation(value = "下载文件")
    @GetMapping("/downloadFile")
    public CommonResult<Void> downloadFile(@RequestParam("id") Integer id,
                                           @RequestParam("type") String type,
                                           HttpServletRequest request,
                                           HttpServletResponse response) {

        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        if (id == null) {
            return CommonResult.failed("文件ID不能为空");
        }

        if (type == null || type.trim().isEmpty()) {
            return CommonResult.failed("文件类型不能为空");
        }

        // 验证type参数
        FileResultVo fileResultVo;
        try {
            if ("knowledge".equalsIgnoreCase(type)) {
                fileResultVo = knowledgeService.getFileResultVoById(id, userId);
            } else if ("material".equalsIgnoreCase(type)) {
                fileResultVo = materialService.getFileResultVoById(id, userId);
            } else if ("piece".equalsIgnoreCase(type)) {
                fileResultVo = pieceService.getFileResultVoById(id, userId);
            } else {
                return CommonResult.failed("文件类型只能是knowledge或material");
            }
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }

        if (fileResultVo == null) {
            return CommonResult.failed("获取文件信息失败");
        }

        String fileName = fileResultVo.getFileName();
        String url = fileResultVo.getUrl();

        if (fileName != null && !fileName.contains(".") && url != null && url.contains(".")) {
            // 尝试补全后缀
            String suffix = url.substring(url.lastIndexOf('.') + 1);
            fileName = fileName + "." + suffix;
        }
        String contentType = FileDownloadUtil.getContentType(fileName);

        try {
            InputStream inputStream = OssUtil.downloadFileFromUrlAsStream(url);
            FileDownloadUtil.downloadFile(inputStream, fileName, contentType, response);
            return CommonResult.success();
        } catch (Exception e) {
            return CommonResult.failed("下载文件失败: " + e.getMessage());
        }
    }

    @ApiOperation(value = "图片代理转发，解决防盗链问题")
    @GetMapping("/proxyImage")
    public ResponseEntity<byte[]> proxyImage(@RequestParam("url") String url) {
        if (url == null || url.trim().isEmpty()) {
            log.warn("图片代理请求url为空");
            return ResponseEntity.badRequest().body(null);
        }
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL imageUrl = new URL(url);
            connection = (HttpURLConnection) imageUrl.openConnection();
            connection.setRequestProperty(HttpHeaders.USER_AGENT, "Mozilla/5.0 ...");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(10000);
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                log.warn("图片代理请求失败，url: {}, 响应码: {}", url, responseCode);
                return ResponseEntity.status(responseCode).body(null);
            }

            String contentType = connection.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                contentType = MediaType.IMAGE_JPEG_VALUE;
            }
            inputStream = connection.getInputStream();
            byte[] imageBytes = StreamUtils.copyToByteArray(inputStream);
            log.info("图片代理成功，url: {}, contentType: {}, size: {}", url, contentType, imageBytes.length);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, contentType)
                    .body(imageBytes);
        } catch (Throwable t) {
            log.error("图片代理异常，url: {}", url, t);
            if (t instanceof MalformedURLException) {
                return ResponseEntity.badRequest().body(null);
            } else if (t instanceof SocketTimeoutException) {
                return ResponseEntity.status(504).body(null);
            } else if (t instanceof FileNotFoundException) {
                return ResponseEntity.status(404).body(null);
            } else {
                return ResponseEntity.status(502).body(null);
            }
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception ignored) {}
            }
            if (connection != null) {
                try { connection.disconnect(); } catch (Exception ignored) {}
            }
        }
    }
} 